<?php

/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace support;

use AlibabaCloud\SDK\Ocrapi\V20210707\Ocrapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizePassportRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

/**
 * Class AlibabaCloud
 * @package support
 */
class AlibabaCloud
{
    /**
     * 使用AK&SK初始化账号Client
     * @return OpenApiClient Client
     *  // 'access_key' => 'LTAI5tEvfD6MtPwvYnxASNXU',
     *  // 'access_secret' => 'AfTpvoDhQaM3K0UApYOSW5QEYMGJNb'
     */
    public static function createClient()
    {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => 'LTAI5tEvfD6MtPwvYnxASNXU',
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => 'AfTpvoDhQaM3K0UApYOSW5QEYMGJNb'
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Ocrapi($config);
    }

    public static function main($url)
    {
        $client = self::createClient();

        $recognizePassportRequest = new RecognizePassportRequest([
            "url" => $url
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->recognizePassportWithOptions($recognizePassportRequest, $runtime);
            // var_dump($res);
            if ($res) {
                $body = str_replace('\\', '', $res->body->data);
                $result = json_decode($body, true);
                return $result;
            } else {
                return [];
            }

            // Log::info('护照识别信息：' . json_encode($res->body));
            // $result = json_decode($body, true);

            // var_dump($result);
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            var_dump($error->message);
            // 诊断地址
            // var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }
}
